package org.phalanx.map;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import org.phalanx.map.xml.MapXMLFileHandler;
import org.phalanx.zip.ZipFileArchiveReader;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;

public class PhalanxMapReader {
	private PhalanxMap map;
	private ZipFileArchiveReader mapFile;
	private MapTileSet tileSet;
	private String cacheDir;
	
	public static final String MAP_XML_FILENAME = "map.xml";
	
	public PhalanxMapReader(MapTileSet defaultTileSet, String cacheDir){
		tileSet = defaultTileSet;
		map = new PhalanxMap();
		this.cacheDir = cacheDir;
	}
	
	public void setMapFile(File newMapFile) {
		try {
			mapFile = new ZipFileArchiveReader(newMapFile);
			map.setMapFilePath(newMapFile.getAbsolutePath());
		} catch (IOException ie){}
	}
	
	public void setMapFileByName(String newMapFileName) {
		try {
			mapFile = new ZipFileArchiveReader(newMapFileName);
			map.setMapFilePath(newMapFileName);
		} catch (IOException ie){}
	}
	
	public ZipFileArchiveReader getArchiveReader(){
		return mapFile;
	}
	
	public PhalanxMap getMap(){
		return map;
	}
	
	public boolean readInMapData(){
		boolean isSuccess = false;

		if (mapFile != null && mapFile.isFileExist()){
			String xmlData = mapFile.getArchivedFileAsString(MAP_XML_FILENAME);

			try {
				if (xmlData != null){
					XMLReader mapSetParser= XMLReaderFactory.createXMLReader();

					MapXMLFileHandler mapXMLHandler = new MapXMLFileHandler(map, tileSet,cacheDir);
					mapSetParser.setContentHandler(mapXMLHandler);
					/*				tileSetParser.parse(xmlData);*/
					mapSetParser.parse(new InputSource(new StringReader(xmlData)));

					isSuccess = true;
				}
			} catch (SAXException sax){ sax.printStackTrace();} catch (IOException ie){ ie.printStackTrace();}
		}

		return isSuccess;
	}
}
